<?php
/**
 * 三通短信接口
 * Copyright (c) 2012, Jiehun.com.cn Inc. All Rights Reserved
 * @author zhanghaozheng@jiehun.com.cn
 * @date 2012-2-11
 * @version 1.0
 * @brief
 **/
require_once dirname(__FILE__).'/ISms.php';
final class SantongSms extends ISms
{
	var $url;
	var $password;
	var $md5psw;
	var $logFunc;
	var $port;
	var $user_name;
	var $curl;
	var $conf;
	var $time_out=10;
	var $connectionT = 10;

	function __construct($conf)
	{
		//平滑过度到新短信接口
		$this->url = $conf['server_url'];
		$this->user_name = $conf['user_name'];
		$this->password = md5($conf['password']);
		$this->sign = $conf['msg_suffix'];
		$this->curl = LibUtil::load('curl');
		$this->conf = $conf;
		if(!empty($conf['time_out']))
		{
			$this->time_out= $conf['time_out'];
		}
		if(!empty($conf['connect_time_out']))
		{
			$this->connectionT = $conf['connect_time_out'];
		}
	}

	/**
	 *发送短信接口
	 *@param string $msg 短信内容
	 *@param string or array $phone 要发送的手机号 如果手机号多个则是一维数组
	 */
	function send($msg,$phone)
	{
		if(empty($msg) || empty($phone))
		{
			return false;
		}

		if(mb_strlen($msg,'utf8')>500)
		{//短信长度不得大于350
			Logger::trace('send sms phoneCount is max :'.$phoneCount);
			return false;
		}
		$phoneCount = 1;
		if(is_array($phone))
		{
			$phone = array_unique($phone);
			$phoneCount = count($phone);
			if($phoneCount>=1000)
			{//短信号码一次发送不得超过1000个
				Logger::trace('send sms phoneCount is max :'.$phoneCount);
				return false;
			}
			$phone = implode(',',$phone);
		}

		//发送短信
		$sendSmsAddress = $this->url.'Submit';
		$message ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ."<message>" . "<account>" . $this->user_name . "</account><password>" . $this->password . "</password>" . "<msgid></msgid><phones>" . $phone . "</phones><content>" . $msg . "</content><subcode>" ."</subcode>" ."<sendtime></sendtime>" ."</message>";
		$requestResult = $this->getResult($this->url.'Submit',$message);
		$rex = '/\<msgid\>(.*?)\<\/msgid\>/i';
		preg_match_all($rex,$requestResult,$matchs);
		return !empty($matchs[1][0])?true:false;
	}

	/**
	 *获取短信余额
	 */
	function getBalance()
	{
		$message ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			."<message>"
			. "<account>"
			. $this->user_name
			. "</account><password>"
			. $this->password
			. "</password>"
			."</message>"; 
		$result = $this->getResult($this->url.'Balance',$message);
		$rex = '/\<number\>(.*?)\<\/number\>/i';
		preg_match_all($rex,$result,$matchs);
		return !empty($matchs[1][0])?intval($matchs[1][0]):0;
	}

	/**
	 *获取请求结果并转换xml
	 */
	function getResult($url,$xmlData)
	{
		$params = array('message' =>$xmlData);
		$requestResult = $this->curl->post($url,$params,array(CURLOPT_TIMEOUT=>$this->time_out,CURLOPT_CONNECTTIMEOUT=>$this->connectionT));
		if($requestResult && $requestResult['code']==200 && !empty($requestResult['content']))
		{
			return $requestResult['content'];
		}
		return $requestResult;
	}

}
